# -- coding: utf-8 --
# @time : 2023/6/2
# @author : 周梦泽
# @file : get_store_info.py
# @software: pycharm
# 获取店铺信息
import json
import re
import traceback
from datetime import datetime

import backoff
import requests

from autoTask.operaitonAid.utils.custom_errors import LoginError
from autoTask.operaitonAid.utils.taobao_requests_headers import page_headers
from autoTask.taobao.redis_key_mange import RedisKey
from autoTask.taobao.taobao_login import Login
from common.logger.log import log_
from common.redis import redis_client
from common.utils import DateUtil
from common.utils.web_page_util import wait_ele_disappear, random_delay, test_page


# https://sycm.taobao.com/portal/coreIndex/getShopMainIndexes.json?dateType=day&dateRange=2023-06-17%7C2023-06-17&device=0&_=1687166922179&token=b3b03f126
# 运营视窗
# https://sycm.taobao.com/s_content/live/overall/overview.json?dateType=day&dateRange=2023-06-17|2023-06-17&_=1687167202506&token=b95b3d30a
# 直播数据

class StoreInfo:
    def __init__(self, params: dict):
        """
        初始化参数
        登录
        :param params:
        """
        self.account = params["account"]
        self.password = params["password"]
        self.query_time_list = [(datetime.now() - timedelta(days=1)).strftime("%Y-%m-%d")] \
            if params["defYesterday"] else params["queryTimeList"]

    def request_api(self, page, query_time):
        """
        请求接口
        :return:
        """
        # page = self.page
        page.get("https://subway.simba.taobao.com")
        headers = page_headers(page)
        datas = {
            "queryParam": str({"startDate": query_time, "endDate": query_time, "effect": -1})
        }
        direct_subway = requests.post(
            url="https://subway.simba.taobao.com/openapi/param2/1/gateway.subway/rpt/rptCampaignByDay$",
            data=datas, headers=headers)
        params = {
            "dateType": "day",
            "dateRange": f"{query_time}|{query_time}"
        }
        operation_viewport = requests.get(
            url="https://sycm.taobao.com/portal/coreIndex/getShopMainIndexes.json",
            headers=headers, params=params)
        # 解析获取到的接口数据
        content1 = operation_viewport.json()["content"].get("data")
        content2 = direct_subway.json()["result"][0]
        response_api_data = {
            "amountPaid": round(content1["payAmt"]["value"], 2) if content1 else None,
            "refundAmount": round(content1["rfdSucAmt"]["value"], 2) if content1 else None,
            "visitorsNum": content1["uv"]["value"] if content1 else None,
            "payTransformRate": round(content1["payRate"]["value"] * 100, 2) if content1 else None,
            "ztcSpend": round(content1["p4pExpendAmt"]["value"], 2) if content1 else None,
            "ylmfSpend": round(content1["cubeAmt"]["value"], 2) if content1 else None,
            "wxtSpend": round(content1["adStrategyAmt"]["value"], 2) if content1 else None,
            "liveRoomAmount": float(content2["costInYuan"]) if content2 else None,
        }
        log_.info(f"获取到的请求信息为：{response_api_data}")
        return response_api_data

    def step_retrieval_data(self, page, query_time):
        """
        使用步骤获取信息
        :return:
        """
        # page = self.page
        # listener = Listener(page)
        # listener.set_targets(targets=['findSum.json', 'findOverProductAccount.json'])
        # listener.listen(count=2, timeout=15)
        # time.sleep(1)
        page.get(
            "https://adbrain.taobao.com/?source=qnpc/#!/strategy/overview?"
            f"source=&startTime={query_time}&endTime={query_time}"
            "&effect=15&unifyType=zhai&tab=adStrategyProductSpeed")
        # 等待页面加载完成
        wait_ele_disappear(page, "x://div/img[@style]", 5)
        random_delay((3, 6))
        wxt_transaction_amount = page("@@mxa=fEpIQolbd_:g@@text():总成交金额", timeout=0)("@mxa^f", timeout=0).text
        page.get(
            "https://tuijian.taobao.com/indexbp-display.html#!"
            "/report/index?effectType=click&effect=15&startTime"
            f"={query_time}&endTime={query_time}")
        random_delay((3, 6))
        # 监听数据包,获取需要的value值
        ylmf_turnover = page("x://div[contains(@mxv, 'chartData')]")("tx:成交金额").next().text
        retrieval_data = {
            "wxtTransactionAmount": float(wxt_transaction_amount.replace(",",
                                                                         "")) if wxt_transaction_amount and wxt_transaction_amount != '-' else None,
            "ylmfTransactionAmount": float(ylmf_turnover.replace(",", "")) if ylmf_turnover != '-' else None,
        }
        log_.info(f"获取到的浏览器信息为：{retrieval_data}")
        return retrieval_data

    # 刷单数据
    def get_brushing_orders(self, page, query_time, pageNum: int = 1):
        if pageNum == 1:
            page.get('https://myseller.taobao.com/home.htm/trade-platform/tp/sold')
        # 发包获取数据
        url = 'https://trade.taobao.com/trade/itemlist/asyncSold.htm?event_submit_do_query=1&_input_charset=utf8 '
        headers = page_headers(page)
        dateBegin = self.time_to13(query_time)
        dateEnd = dateBegin + 86400000 - 1
        data = {
            'dateBegin': dateBegin, 'dateEnd': dateEnd, 'pageNum': pageNum,
            'action': 'itemlist/SoldQueryAction', 'orderStatus': 'ALL', 'pageSize': 15,
        }
        response = requests.post(url, headers=headers, data=data).json()
        info = {
            'fillOrderNum': 0,
            'brushOrdersAmount': 0.0
        }
        for row in response['mainOrders']:
            if row['statusInfo']['text'] not in ['卖家已发货', '交易成功']:
                continue
            if row['extra']['sellerFlag'] != 3:
                continue
            info['fillOrderNum'] += 1
            info['brushOrdersAmount'] += float(row['payInfo']['actualFee'])
        if int(response['page']['totalPage']) > pageNum:
            next_info = self.get_brushing_orders(page, query_time, pageNum + 1)
            info['fillOrderNum'] += next_info['fillOrderNum']
            info['brushOrdersAmount'] += next_info['brushOrdersAmount']
        return info

    # # 直通车 成交金额
    # def ztc_amount(self, page, query_time):
    #     url = f'https://subway.simba.taobao.com/index.jsp#!/report/bpreport/campaign/index?page=1&start={query_time}&end={query_time}'
    #     page.get(url)
    #     page.wait.load_start(timeout=2)
    #     amount = page.ele('x://ul[@class="hYME_lhIaxZ"]/li[6]//p[@class="hYME_lhIaya mt10"]').text
    #     amount = re.sub('元', '', amount)
    #     amount = re.sub(',', '', amount)
    #     return float(amount)

    @staticmethod
    def time_to13(date_string):
        datetime_object = datetime.datetime.strptime(date_string, "%Y-%m-%d")
        timestamp = datetime_object.timestamp()
        timestamp = timestamp * 1000
        return int(timestamp)

    @staticmethod
    def build_key(store_name: str, query_time: str):
        key_prefix = RedisKey.dpxx.key
        key = key_prefix + f"{store_name}:{query_time}"
        return key

    # @backoff.on_exception(backoff.constant, Exception, max_tries=3,
    #                       interval=5, on_backoff=lambda details: log_.error(traceback.format_exc()))
    # @backoff.on_predicate(backoff.fibo, lambda e: isinstance(e, (LoginError,)), max_tries=1)
    def __call__(self):
        """
        调用
        :return:
        """
        page, store_name = Login(self.account, self.password).execute()
        store_info_list = []
        for query_time in self.query_time_list:
            key = self.build_key(store_name, query_time)
            data = redis_client.get(key, type_=str)
            store_info = json.loads(data) if data else None
            # 如果缓存中不存在，就去获取
            if not store_info:
                # 万相台—运营视窗
                wxt_ylmf_turnover = self.step_retrieval_data(page, query_time)
                # 运营视窗-直通车
                yysc_ztc_response_data = self.request_api(page, query_time)
                # 千牛刷单数据
                myseller_brush_order_data = self.get_brushing_orders(page, query_time)
                store_info = {
                    "storeName": store_name,
                    "dataDate": query_time,
                    **wxt_ylmf_turnover,
                    **yysc_ztc_response_data,
                    **myseller_brush_order_data
                }
                random_delay((20, 35))
                # 随机延迟，避免频繁
                redis_client.put(key, store_info, ex=DateUtil.seconds_until_end_of_day(1))

            store_info_list.append(store_info)
            # store_info_json = json.dumps(store_info, ensure_ascii=False)
            log_.info(f"获取到的店铺信息为：{store_info}")
        return store_info_list


if __name__ == '__main__':
    from datetime import datetime, timedelta

    print()
